package edu.olin.scheduler.gui.schedule;

import edu.olin.scheduler.common.*;
import edu.olin.scheduler.gui.*;
import java.util.Iterator;
import javax.swing.BoxLayout;
import javax.swing.JPanel;

public class ScheduleDisplay extends JPanel implements GUIPrefs.Listener, Schedule.Listener {
    
    private SingleDayDisplay[] displays;
    private Schedule schedule;

    private void setWeekendsVisible(boolean weekendsVisible){
        displays[0].setVisible(weekendsVisible);
        displays[6].setVisible(weekendsVisible);
        }
    
    public ScheduleDisplay(Schedule schedule){
        super(true);
        if(schedule==null){ throw new NullPointerException("Cannot display a null schedule"); }
        schedule.addListener(this);
        this.schedule = schedule;
        GUIPrefs.addListener(this);
        setBackground(GUIPrefs.getDailyBGColor());
        setOpaque(true);
        setLayout(new BoxLayout(this,BoxLayout.X_AXIS));
        initDisplays();
        rebuildDisplays();
        setWeekendsVisible(false);
        }
    
    private void initDisplays(){
        displays = new SingleDayDisplay[7];
        for(int i=0; i<7; i++){
            displays[i] = new SingleDayDisplay(i);
            this.add(displays[i]);
            }
        }
    
    private void rebuildDisplays(){
        //Build the individual MeetingDisplays from the Schedule
        //If the schedule is later changed, re-invoke this method
        //to update the ScheduleDisplay
        //drop all the old MeetingDisplays
        if(displays!=null){
            for(int i=0; i<displays.length; i++){
                if(displays[i]==null){ continue; }
                displays[i].clear();
                }
            }
        //Add the new MeetingDisplays
        Iterator<Course> itr = schedule.getCourses().iterator();
        while(itr.hasNext()){
            Course c = itr.next();
            if(c==null){ continue; }
            Meeting[] m = c.getMeetings();
            MeetingDisplay[] md = new MeetingDisplay[m.length];
            for(int i=0; i<md.length; i++){
                md[i] = new MeetingDisplay(m[i]);
                displays[md[i].getMeeting().dayOfWeek()].addMeetingDisplay(md[i]);
                }
            }
        //update our layout
        doLayout();
        repaint();
        }
    
    public void doLayout(){
        super.doLayout();
        for(int i=0; i<7; i++){
            displays[i].doLayout();
            }
        }
    
    public void guiPrefsChanged(){
        setBackground(GUIPrefs.getDailyBGColor());
        setWeekendsVisible(GUIPrefs.isWeekendVisible());
        doLayout();
        }

    public void scheduleChanged() {
        rebuildDisplays();
        doLayout();
        repaint();
        }

    public Schedule getSchedule() {
        return schedule;
        }

    }
